<?php

namespace App\Http\Services;

use App\Http\Model\FinanceDiamond;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\SystemConfig;
use Exception;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Hint;
use App\Http\Model\User;
use App\Http\Model\Gift;
use App\Http\Model\GiftBag;
use App\Http\Model\HopeLuckDraw;
use App\Http\Model\Mall;
use App\Http\Model\System;
use App\Model\FinanceWallet;
use App\Modules\LuckDraw\Models\UserPropLogModel;
use App\Modules\LuckDraw\Models\UserPropModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use stdClass;

class HopeDrawServices extends CommonServices
{
    protected $userModel;
    protected $giftModel;
    protected $luckDrawModel;
    protected $customService;
    protected $giftBag_model;
    protected $systemModel;
    protected $msgService;
    protected $financeUserWallet;
    protected $FinanceDiamond;
    protected $userPropModel;
    protected $mall_model;
    protected $luckId;
    protected $spPopGifts;
    protected $senHeadGoodsId;
    protected $popSeaBoxNum = 'WISHPOOL:POPBOX:NUM';
    protected $todayLuckPopKey = 'WISHLUCK:POP';//今日确认弹窗
    protected $error_log = 'error_luck_draw_cost';//扣钻石日志
    protected $senStarGoodsId;
    protected $exGiftIdsList = 'LUCKDRAW:EX:GIFTLIST';//心心相印投入展示礼物

    public function __construct()
    {
        parent::__construct();

        $this->userModel = new User();
        $this->giftModel = new Gift();
        $this->luckDrawModel = new HopeLuckDraw();
        $this->customService = new CustomServices();
        $this->giftBag_model = new GiftBag();
        $this->systemModel = new System();
        $this->financeUserWallet = new FinanceUserWallet();
        $this->msgService = new MsgServices();
        $this->FinanceDiamond = new FinanceDiamond();
        $this->mall_model = new Mall();
        $this->luckId = 1000;
        $this->spPopGifts = [473,474,475]; //TODO 玩法套盒特殊礼物爆出礼物id
        $this->senHeadGoodsId = 119;//TODO 购买资产赠送头像框
        $this->senStarGoodsId = 4;//TODO 星球夺宝赠送头像框

    }

    /**
     * 心心相印全服中奖记录列表
     */
    public function awardListV2($page, $limit, $userId = '', $luckId = '')
    {
        $data = [];
        do {
            // TODO 数据量大临时优化 999999999
            $where['luck_id'] = $luckId;
//            $where['id'] = 18765700;
//            $where['created_at_st'] = date('Y-m-d 00:00:00', time());
            $list = $this->luckDrawModel->awardListV2($page, $limit, $where);

            $listEx = [];
            if (!empty($list)) {
                $userIds = array_column($list, 'user_id');
                $userList = $this->userModel->getUserInfoByIds($userIds);
                $userList = array_column($userList, null, 'user_id');

                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'image', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach ($list as $key => $val) {
                    $newArr = [];
                    if (empty($userList[$val['user_id']])) {
                        continue;
                    }
                    if (empty($giftList[$val['gift_id']])) {
                        continue;
                    }
                    $newArr['userId'] = $val['user_id'];
                    $newArr['giftId'] = $val['gift_id'];
                    $newArr['name'] = $giftList[$val['gift_id']]['name'];
                    $newArr['price'] = $giftList[$val['gift_id']]['price'];
                    $newArr['num'] = $val['gift_num'];
                    $newArr['createdAt'] = $val['created_at'];
                    $newArr['nickname'] = $userList[$val['user_id']]['nickname'];
                    $newArr['uuid'] = $userList[$val['user_id']]['uuid'];
                    $newArr['avatar'] = build_image(json_decode($userList[$val['user_id']]['portrait'], true)[0]);
                    $newArr['image'] = build_image($giftList[$val['gift_id']]['image']);
                    $newArr['sp_type'] = $val['is_sp'];

                    $listEx[] = $newArr;
                }
            }


            $data['list'] = $listEx;
        } while (false);

        return $data;
    }

    private function _getAperture($price)
    {
        $aperture = 0;
        if ($price >= 0 and $price < 100000) {
            $aperture = 1;
        } elseif ($price >= 100000 and $price < 300000) {
            $aperture = 2;
        } elseif ($price >= 300000) {
            $aperture = 3;
        } else {
            $aperture = 0;
        }
        return $aperture;
    }

    /**
     * 心心相印奖池配置剩余数量
     */
//    public function luckDrawPoolConfigNum($poolId)
//    {
//        $code = Hint::SUCCESS;
//        $msg = '';
//        $data = [];
//        do {
//            try {
//                if (empty($poolId)) {
//                    $code = Hint::PARAM_ERROR;
//                    break;
//                }
//                $poolList = $this->luckDrawModel->getLuckDrawPoolConfig($poolId);
//                if (empty($poolList)) {
//                    $code = Hint::PARAM_ERROR;
//                    break;
//                }
//
//                $hasList = $this->luckDrawModel->getLuckDrawPoolData($poolList['luck_id'], $poolId);
//                $hasList = array_column($hasList, 'num', 'id');
//
//                $giftIds = array_column($poolList['pool'], 'id');
//                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price']);
//                $giftList = array_column($giftList, null, 'gift_id');
//
//                foreach ($poolList['pool'] as $key => $val) {
//                    $val['luck_id'] = $poolList['luck_id'];
//                    $val['pool_id'] = $poolList['id'];
//                    $val['gift_id'] = $val['id'];
//                    $val['gift_num'] = $val['num'];
//                    $val['gift_name'] = empty($giftList[$val['id']]['name']) ? '' : $giftList[$val['id']]['name'];
//                    $val['gift_price'] = empty($giftList[$val['id']]['price']) ? 0 : $giftList[$val['id']]['price'];
//                    $val['less_num'] = empty($hasList[$val['id']]) ? 0 : $hasList[$val['id']];
//                    $val['draw_num'] = $val['num'] - $val['less_num'];
//
//                    $data[] = $val;
//                }
//            } catch (\Exception $e) {
//                $code = Hint::ERROR;
//                $msg = '异常:' . $e->getMessage();
//                break;
//            }
//        } while (false);
//
//        return compact('code', 'msg', 'data');
//    }


    /**
     * 心心相印池子外显概率列表
     */
    public function poolAwardListV2($luckId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($luckId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $list = $this->luckDrawModel->getWishLuckGift();
            $listEx = [];
            if(!empty($list)) {
                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds,['gift_id','name','image','price', 'gift_type']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach($list as $key=>$val) {
                    if(empty($giftList[$val['gift_id']])) {
                        continue;
                    }
                    $item = [];
                    $item['gift_id'] = $val['gift_id'];
                    $item['name'] = $giftList[$val['gift_id']]['name'];
                    if($giftList[$val['gift_id']]['gift_type'] == 13){
                        $item['name'] = '神秘彩蛋';
                        $item['price'] = '88800+';
                    }else{
                        $item['price'] = $giftList[$val['gift_id']]['price'];
                    }
                    $item['image'] = build_image($giftList[$val['gift_id']]['image']);
                    $item['top_right_corner'] = build_image($this->giftGetBanner($item['gift_id']));
                    $item['sp_img'] = build_image($this->specialGiftImg($item['gift_id']));
                    $item['sp_type'] = in_array($giftList[$val['gift_id']]['gift_type'],[12,13]) ? $giftList[$val['gift_id']]['gift_type'] : 0;
                    $listEx[] = $item;
                }
            }

            $data = $listEx;
            $sortPrice = array_column($data, 'price');
            $sortSptype = array_column($data, 'sp_type');
            array_multisort($sortSptype, SORT_DESC,$sortPrice, SORT_DESC,  $data);
        } while (false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 获取滚动记录
     */
    public function marquee($top)
    {
        $code = Hint::SUCCESS;
        $msg = 'OK';
        $data = [];
        do {
            $res = $this->luckDrawModel->marquee($top);
            if (empty($res)) {
                break;
            }
            $giftIds = array_column($res, 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'image', 'price']);
            $giftList = array_column($giftList, null, 'gift_id');

            $userIds = array_column($res, 'user_id');
            $userList = $this->userModel->getUserInfoByIds($userIds);
            $userList = array_column($userList, null, 'user_id');
            foreach ($res as $k => $v) {
                $newArr = [
                    'type' => 1, //奖品类型 1、礼物 2、商品 
                    'luckId' => $v['pool_id'],
                    'userId' => $v['user_id'],
                    'awardId' => $v['id'],
                    'timeLimit' => 0,
                    'name' => $giftList[$v['gift_id']]['name'],
                    'image' => build_image($giftList[$v['gift_id']]['image']),
                    'price' => $giftList[$v['gift_id']]['price'],
                    'num' => $v['gift_num'],
                    'aperture' => $this->_getAperture($giftList[$v['gift_id']]['price']),
                    'nickname' => $userList[$v['user_id']]['nickname'],
                ];
                $data[] = $newArr;
            }
        } while (false);
        return compact('code', 'data', 'msg');
    }

    /**
     * 抽奖
     */
    public function wishPoolDraw($userId, $num, $roomId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $luckId = 1000;
        $hookPoolId = 1003;
        $now = time();
        do {
            $num = abs($num);
            $oldNum = $num;
            //配置
            $config = $this->luckDrawModel->getWishPoolConfig();
            if (empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $needNum = $config['need_num'] * $num;

            //个人池用户
            $poolUser = $this->luckDrawModel->getWishLuckPoolUserId($userId);

            //获取用户当前抽奖的奖池
            //奖池
            $pool = $this->luckDrawModel->getWishLuckPool();
            $basePoolList = []; //普通池的
            $userPoolList = []; //用户个人池的
            foreach ($pool as $val) {
                if ($val['status'] != 1) {
                    continue;
                }
                //奖池配置数据
                $poolConfig = $this->luckDrawModel->getWishLuckPoolConfig($val['id']);
                if (empty($poolConfig)) {
                    continue;
                }
                $val['poolConfig'] = $poolConfig;
                //普通池
                if ($val['pool_type'] == 1) {
                    $basePoolList[] = $val;
                }
                //用户个人池
                if (in_array($val['pool_type'], [2, 3])) {
                    if (!empty($poolUser) && !empty($poolUser['pool_id']) && $val['id'] == $poolUser['pool_id']) {
                        $userPoolList[] = $val;
                    }
                }
            }
            $poolList = []; //已开启的奖池
            $giftToItemNo = []; //奖池礼物对应的奖池序号
            $ifdrawInUserPool = 0; //是否在个人池抽奖 0=否 1=是
            if (!empty($poolUser) && !empty($userPoolList)) {
                $poolList = $userPoolList;
                $ifdrawInUserPool = 1;
            } else {
                $poolList = $basePoolList;
            }
            if (empty($poolList)) {
                $code = Hint::WAIT_OPEN;
                break;
            }
            $giftToItemNo = array_column($poolList[0]['poolConfig'], 'item_no', 'gift_id');

            //爱心币价格
            $luckDrawInfo = $this->luckDrawModel->luckDrawInfo($luckId);
            $luckDrawPrice = empty($luckDrawInfo['price']) ? 0 : $luckDrawInfo['price'];

            //用户爱心币数量
            $userLuckDrawProp = $this->luckDrawModel->getLuckDrawUserProp($userId, $hookPoolId);
            if ($userLuckDrawProp['avail'] < $needNum) {
                //新逻辑自动转换兑换爱心币,在redis名单中的代表新版本用户抽奖
                if(Redis::SISMEMBER($this->todayLuckPopKey,$userId)){
                    $changeStatus = $this->autoExchangeCard($userLuckDrawProp, $needNum, $luckDrawPrice, $userId);
                    if($changeStatus['code'] != Hint::SUCCESS){
                        $code = $changeStatus['code'];
                        $msg = $changeStatus['msg'];
                        break;
                    }
                }else{
                    $code = Hint::LUCK_DRAW_PROP_NOT_ENOUGH;
                    $msg = '爱心币数量不足';
                    break;
                } 
            }

            //扣爱心币
            $decrRes = $this->luckDrawModel->decrLuckDrawUserProp($userId, $hookPoolId, $needNum,'心心相印消耗');
            if (!$decrRes) {
                $code = Hint::LUCK_DRAW_PROP_NOT_ENOUGH;
                $msg = '爱心币数量不足';
                break;
            }

            //人气票发放
            $this->customService->SendTicket($userId, $needNum, $luckDrawPrice, 7);

            //用户信息
            $userInfo = $this->userModel->get_users_by_ids([$userId]);
            $userInfo = array_column($userInfo, null, 'user_id');
            $userInfo = $userInfo[$userId];

            //用户总抽奖记录数
            if ($ifdrawInUserPool) {
                //个人池用户
                $drawNumNow = $drawNum = $poolUser['draw_num'];
            } else {
                //普通
                $drawNumNow = $drawNum = $this->luckDrawModel->getDrawCountByThreeDays($userId);
            }

            //白名单
            $whiteListNow = $whiteList = $this->luckDrawModel->getWishLuckWhite($userId);

            //订单记录
            $orderInfo = [
                'user_id' => $userId,
                'num' => $num,
                'prop_num' => $needNum,
                'prop_diamond_num' => $needNum * $luckDrawPrice,
                'reward_diamond_num' => 0,
                'created_at' => date('Y-m-d H:i:s', $now),
            ];
            $orderId = $this->luckDrawModel->addWishLuckOrder($orderInfo);
            if (empty($orderId)) {
                $code = Hint::ERR_SYS_FAIL;
                break;
            }

            //抽奖
            $drawLogList = [];
            try {
                $whiteId = 0;
                $sexBoxArr = [];
                for ($i = 1; $i <= $num; $i++) {
                    $drawNumNow = $drawNumNow + 1;
                    $drawLog = [];
                    $drawLog['draw_no'] = $i;
                    $drawLog['gift_id'] = 0;
                    $drawLog['white_id'] = 0;
                    $drawLog['pool_id'] = 0;
                    $drawLog['item_no'] = 0;
                    //白名单
                    if (!empty($whiteListNow)) {
                        $whiteInfo = array_shift($whiteListNow);
                        //查看抽取的奖励是否是特殊奖励若是玩法套盒礼物则重新抽取玩法套盒里的礼物
                        $configPoolId = array_column($poolList[0]['poolConfig'],null,'gift_id');
                        $isSpGift = $this->luckDrawModel->getWishLuckSpPoolConfig(0, $configPoolId[$whiteInfo['gift_id']]['id'], $whiteInfo['gift_id'], 12);
                        //查找开启池中配置的神秘珍宝id
                        $colorIds = $this->luckDrawModel->getColorIds();
                        $is_sp = 0;
                        if(!empty($isSpGift)){
                            foreach($isSpGift as $spVal){
                                for($is = 0; $is< $spVal['gift_num']; $is++){
                                    $arr= [
                                        'gift_id' => $spVal['child_gift_id'],
                                        'white_id' => $whiteInfo['id'],
                                        'pool_id' => $whiteInfo['id'],
                                        'item_no' => $spVal['id'],
                                        'is_sp' => 12
                                    ];
                                    $i = $i+1;
                                    array_push($drawLogList,$arr);
                                }
                            } 
                            $num = $oldNum+1;
                            $this->luckDrawModel->setNextDrawSp($userId);
                        }elseif(in_array($whiteInfo['gift_id'],$colorIds)){
                            $drawLog['gift_id'] = $whiteInfo['gift_id'];
                            $drawLog['white_id'] = $whiteInfo['id'];
                            $drawLog['item_no'] = empty($giftToItemNo[$whiteInfo['gift_id']]) ? 11 : $giftToItemNo[$whiteInfo['gift_id']];
                            $drawLog['is_sp'] = 13;
                            $whiteStatus = 1;
                        }else{
                            $drawLog['gift_id'] = $whiteInfo['gift_id'];
                            $drawLog['white_id'] = $whiteInfo['id'];
                            $drawLog['item_no'] = empty($giftToItemNo[$whiteInfo['gift_id']]) ? 11 : $giftToItemNo[$whiteInfo['gift_id']];
                            $drawLog['is_sp'] = $is_sp;
                            $whiteStatus = 1;
                        }
                        $whiteId = $whiteInfo['id'];
                    } else {
                        $usePool = []; //使用的奖池
                        //在范围的
                        foreach ($poolList as $val) {
                            if ($val['min_num'] <= $drawNumNow && $drawNumNow <= $val['max_num']) {
                                $usePool = $val;
                            }
                        }
                        //上一个
                        $prevNum = 0;
                        if (empty($usePool)) {
                            foreach ($poolList as $val) {
                                if ($val['max_num'] <= $drawNumNow && $prevNum <= $val['max_num']) {
                                    $usePool = $val;
                                    $prevNum = $val['max_num'];
                                }
                            }
                        }
                        //下一个
                        $nextNum = 0;
                        if (empty($usePool)) {
                            foreach ($poolList as $val) {
                                if ($val['min_num'] >= $drawNumNow && ($nextNum == 0 || $nextNum >= $val['min_num'])) {
                                    $usePool = $val;
                                    $nextNum = $val['min_num'];
                                }
                            }
                        }
                        //还是没有取第一个
                        if (empty($usePool)) {
                            $usePool = $poolList[0];
                        }

                        $poolConfigMap = array_column($usePool['poolConfig'], null, 'id');
                        //抽取 
                        if (in_array($usePool['pool_type'], [2, 3])) {
                            //投入池逻辑
                            $isExGiftDraw = $this->checkExDraw($userId, $usePool['id'], $drawNumNow);
                            if($isExGiftDraw){
                                //随机在投入奖池抽取
                                $poolConfigId = $this->luckDrawModel->drawWishExWheel($usePool['id']);
                                //获取对应投入奖池配置ID
                                $exUsePoolInfo = $this->luckDrawModel->getExPoolGifts($usePool['id']);
                                $poolConfigMap = array_column($exUsePoolInfo, null, 'id');
                            }else{
                                //个人池
                                $poolConfigId = $this->luckDrawModel->drawWishLuckUser($usePool['id'], $userId);
                            }
                        } else if(!empty($whiteId) && in_array($oldNum,[10,100])){
                                //白名单配置五动乾坤时候剩余数量需要指定礼物id爆出
                                $poolConfigId = $this->drawSpGifts($usePool['id']);
                        }else{
                            //投入池逻辑
                            $isExGiftDraw = $this->checkExDraw($userId, $usePool['id'], $drawNumNow);
                            if($isExGiftDraw){
                                //随机在投入奖池抽取
                                $poolConfigId = $this->luckDrawModel->drawWishExWheel($usePool['id']);
                                //获取对应投入奖池配置ID
                                $exUsePoolInfo = $this->luckDrawModel->getExPoolGifts($usePool['id']);
                                $poolConfigMap = array_column($exUsePoolInfo, null, 'id');
                            }else{
                                //普通
                                $poolConfigId = $this->luckDrawModel->drawWishLuck($usePool['id']);
                            }
                        }

                        $popGiftId = $poolConfigMap[$poolConfigId]['gift_id'];
                        $poolId = $poolConfigMap[$poolConfigId]['pool_id'];
                        $drawLog['gift_id'] = $popGiftId;
                        $drawLog['white_id'] = 0;
                        $drawLog['pool_id'] = $poolId;
                        $drawLog['item_no'] = $poolConfigMap[$poolConfigId]['item_no'];
                        $drawLog['pool_config_id'] = $poolConfigId;
                        //判断是否是彩蛋玩法礼物中的礼物
                        $colorGift = $this->luckDrawModel->checkColorGift($drawLog['gift_id'], $poolConfigId, $userId);
                        $drawLog['is_sp'] = $colorGift; 
                    }
                    if($drawLog['gift_id'] != 0){
                        $drawLogList[] = $drawLog;
                    }
                }
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                write_log('error_hopeLuck', 'wishLuckDraw 抽奖失败', ['orderId' => $orderId, 'message' => $e->getMessage(), 'line' => $e->getLine()]);
                $data = new \stdClass();
                break;
            }
            $drawLogList = $this->roundHundred($userId, $drawLogList, $oldNum, $poolId, $poolConfigId, $poolConfigMap, $whiteId);
            
        
            //累加用户总抽奖记录数
            $this->luckDrawModel->incrUserDrawThreeDayNum($userId, $num);
            $giftIds = array_column($drawLogList, 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price', 'image']);
            $giftList = array_column($giftList, null, 'gift_id');

            //抽奖保存
            DB::beginTransaction();
            try {
                $rewardDiamondNumAll = 0;
                
                //新增心心相印抽奖记录
                foreach ($drawLogList as $key => $val) {
                    $val['order_id'] = $orderId;
                    $val['user_id'] = $userId;
                    $val['prop_num'] = $config['need_num'];
                    $val['gift_num'] = 1;
                    $val['prop_diamond_num'] = $val['prop_num'] * $luckDrawPrice;
                    $val['reward_diamond_num'] = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                    $val['created_at'] = date('Y-m-d H:i:s', $now);
                    $val['is_sp'] = isset($val['is_sp']) ? $val['is_sp'] : 0;
                    unset($val['pool_config_id']);
                    $id = $this->luckDrawModel->addWishLuckDraw($val);
                    //奖励价值钻石数
                    $rewardDiamondNumAll = $rewardDiamondNumAll + $val['reward_diamond_num'];

                    //白名单
                    if (!empty($val['white_id'])) {
                        $this->luckDrawModel->updateWishLuckWhite($val['white_id'], $orderId);
                    }
                    $gift_num = 1;
                    //送礼物
                    $this->giftBag_model->inc((int)$userId, 0, (int)$val['gift_id'], $gift_num, 1000);
                    
                    $drawLogList[$key] = $val;
                }
                
                //更新订单
                $this->luckDrawModel->updateWishLuckDraw($orderId, $rewardDiamondNumAll);
                //更新个人池用户记录
                if ($ifdrawInUserPool && $val['white_id'] == 0) {
                    $this->luckDrawModel->updateWishLuckUserPoolLog($poolUser['id'], $orderInfo['prop_diamond_num'], $rewardDiamondNumAll, $orderInfo['num']);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_hopeLuck', 'wishLuckDraw 抽奖保存', ['orderId' => $orderId, 'drawLogList' => $drawLogList, 'message' => $e->getMessage(), 'line' => $e->getLine()]);
                $data = new \stdClass();
                break;
            }
            //更新心心相印用户每日抽奖数据统计缓存
            $this->luckDrawModel->updateWishLuckUserDay($userId, $orderInfo['prop_diamond_num'], $rewardDiamondNumAll, $orderInfo['num']);

            //个人池用户自动处理移入移出
            $this->luckDrawModel->handleWishLuckUserPool($userId, $poolUser);

            //汇总返回值
            $resList = [];
            $frontList = [];
            $resList = $this->luckDrawModel->getDrawList($orderId);
            foreach ($resList as $k=>$vals) {
                    $item = [];
                    $item['type'] = 1;
                    $item['luckId'] = $this->luckId;
                    $item['userId'] = $userId;
                    $item['awardId'] = $orderId;
                    $item['timeLimit'] = 0;
                    $item['name'] = empty($giftList[$vals['gift_id']]['name']) ? '' : $giftList[$vals['gift_id']]['name'];
                    $item['price'] = (int) (empty($giftList[$vals['gift_id']]['price']) ? 0 : $giftList[$vals['gift_id']]['price']);
                    $item['image'] = empty($giftList[$vals['gift_id']]['image']) ? '' : build_image($giftList[$vals['gift_id']]['image']);
                    $item['aperture'] = $this->_getAperture($item['price']);
                    $item['nickname'] = $userInfo['nickname'];
                    $item['num'] = $vals['gift_num'];
                    $item['sp_type'] = $vals['is_sp'];
                    $item['top_right_corner'] = build_image($this->giftGetBanner(0,$vals['is_sp']));
                    $resList[$k] = $item;
            }
            $resList = array_values($resList);
            $sortPrice = array_column($resList, 'price');
            $sortSptype = array_column($resList, 'sp_type');
            array_multisort($sortSptype, SORT_DESC,$sortPrice, SORT_DESC,  $resList);

            //房间内游戏公屏游戏消息
            if ($roomId > 10) {
                //查询飘屏中设置的飘屏限制钻石数,因为公屏限制和飘屏限制一致
                $fullScreen = $this->systemModel->getFullScreen(72);
                if (empty($fullScreen)) {
                    return false;
                }
                 foreach ($resList as $val) {
                     if ($val['price'] >= $fullScreen['special_full_screen_diamond']) {
                         $this->msgService->worldHopeDrawMsg(['nickname' => $userInfo['nickname'], 'user_id' => $userInfo['user_id'], 'placeName' => '在心心相印中', 'giftName' => $val['name'], 'giftPrice' => $val['price'], 'giftNum' => $val['num'], 'giftImg' => $val['image']]);
                     }
                 }
            }
            $data['list'] = $resList;
            $data['order_id'] = $orderId;
            $data['reward_diamond_num'] = $rewardDiamondNumAll;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //礼物获取角标
    public function giftGetBanner($giftId, $gift_type=0)
    {
        $icon = '';
        //查看礼物类型
        $giftInfo = $this->giftModel->get_gift($giftId);
        if($giftInfo['gift_type'] == 12 || $gift_type == 12){
            $icon = '/icon/seabox.png';
        }elseif($giftInfo['gift_type'] == 13 || $gift_type == 13){
            $icon = '/icon/seacolor.png';
        }
        return $icon;
    }

    //礼物获取角标
    public function specialGiftImg($giftId, $gift_type=0)
    {
        $icon = '';
        //查看礼物类型
        $giftInfo = $this->giftModel->get_gift($giftId);
        if($giftInfo['gift_type'] == 13 || $gift_type == 13){
            $icon = '/icon/sea_color_gift.png';
        }
        return $icon;
    }

    /**
     * 飘屏处理
     */
    public function wishLuckDrawFull($orderId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $luckId = 1000;
        $now = time();
        do {
            if (empty($orderId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $orderInfo = $this->luckDrawModel->orderAwardList($orderId);
            if (empty($orderInfo)) {
                break;
            }
            //配置
            $config = $this->luckDrawModel->getWishPoolConfig();
            if (empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //钩子价格
            $luckDrawInfo = $this->luckDrawModel->luckDrawInfo($luckId);
            $luckDrawPrice = empty($luckDrawInfo['price']) ? 0 : $luckDrawInfo['price'];

            //用户信息
            $userInfo = $this->userModel->get_users_by_ids([$orderInfo['user_id']]);
            $userInfo = array_column($userInfo, null, 'user_id');
            $userInfo = $userInfo[$orderInfo['user_id']];

            $giftIds = array_column($orderInfo['drawList'], 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price', 'image']);
            $giftList = array_column($giftList, null, 'gift_id');

            //飘屏
            foreach ($orderInfo['drawList'] as $val) {
                $giftPrice = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                $giftName = empty($giftList[$val['gift_id']]['name']) ? 0 : $giftList[$val['gift_id']]['name'];
                $rate = ($val['reward_diamond_num'] / $val['prop_diamond_num']) * 100;
                //$rate >= $config['full_rate']
                if ($val['reward_diamond_num'] >= 5200) {
                    $this->msgService->sendFullScreen(72, null, ['userName' => $userInfo['nickname'], 'diamondNum' => $giftPrice, 'giftName' => $giftName, 'giftNum' => $val['gift_num']], [], ['giftPrice' => $giftPrice]);

                    //飘屏逻辑sptype=0正常发普通飘屏
//                    if($val['is_sp'] == 0){
//                        $this->msgService->sendFullScreen(72, null, ['userName' => $userInfo['nickname'], 'diamondNum' => $giftPrice, 'giftName' => $giftName, 'giftNum' => $val['gift_num']], [], ['giftPrice' => $giftPrice]);
//                        //特殊飘屏
//                        $normalFullScreen = $this->systemModel->getFullScreen(22);//特殊飘屏信息
//                        if($giftPrice >= $normalFullScreen['special_full_screen_diamond'] && $normalFullScreen['special_full_screen_diamond'] != 0){
//                            $this->msgService->sendFullScreen(70,null,['userName'=>$userInfo['nickname'], 'diamondNum'=>$giftPrice, 'giftName'=>$giftName, 'giftNum'=>$val['gift_num']],[],['giftPrice'=>$giftPrice]);
//                        }
//                    }
                    //sptype == 12 玩法套盒飘屏
//                    if($val['is_sp'] ==  12){
//                        $this->msgService->sendFullScreen(73, null, ['userName' => $userInfo['nickname'], 'diamondNum' => $giftPrice, 'giftName' => $giftName, 'giftNum' => $val['gift_num']], [], ['giftPrice' => $giftPrice]);
//                    }
//                    //sptype == 13 彩蛋飘屏
//                    if($val['is_sp'] == 13){
//                        $this->msgService->sendFullScreen(74, null, ['userName' => $userInfo['nickname'], 'diamondNum' => $giftPrice, 'giftName' => $giftName, 'giftNum' => $val['gift_num']], [], ['giftPrice' => $giftPrice]);
//                    }
                }

                
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 获取活动规则
     */
    public function getRule()
    {
        $config = $this->luckDrawModel->getWishPoolConfig();
        if (empty($config)) {
            return [];
        }
        $data = $config['rule'];
        return $data;
    }

    /**
     * 兑换告白币??
     */
    public function exchange($num, $userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $luckId = 1000;
        do {
            //获取所需钻石总额
            $luckDrawInfo = $this->luckDrawModel->luckDrawInfo($luckId);
            $luckDrawPrice = empty($luckDrawInfo['price']) ? 0 : $luckDrawInfo['price'];
            $needTotalDiamond = $luckDrawPrice * $num;
            //查询当前用户可用钻石
            $walletData = $this->financeUserWallet->get_wallet($userId);
            if ($walletData['diamond_balance'] < $needTotalDiamond) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            DB::beginTransaction();
            try {
                //扣除钻石
                $this->FinanceDiamond->inc($userId, 0, 0, 6, -$needTotalDiamond, '兑换钩子');
                //增加道具
                $ok = $this->luckDrawModel->addProp($luckId, $userId, $num);
                //道具保存成功则增加日志
                if ($ok) {
                    $ok = $this->luckDrawModel->addPropLog($luckId, $userId, 1000, $num);
                }
                //赠送头像框
                $goodId = 13;
                $goodInfo = $this->mall_model->getMallGoodByGoodsId($goodId);
                if (empty($goodInfo)) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $skuList = $this->mall_model->getSkuDataByGoods($goodId);
                if (empty($skuList[0])) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $goodMap[$goodId]['goods_name'] = $goodInfo['goods_name'];
                $goodMap[$goodId]['goods_type'] = $goodInfo['goods_type'];
                $goodMap[$goodId]['sku_id'] = $skuList[0]['sku_id'];
                //有效期
                $timeLimit = $num * 3600;
                //商品增加
                $this->mall_model->shoppingAct(
                    11,
                    $userId,
                    $goodId,
                    $goodMap[$goodId]['goods_name'],
                    $goodMap[$goodId]['goods_type'],
                    $goodMap[$goodId]['sku_id'],
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    2
                );
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_hopeLuck', 'error 兑换告白币', ['msg' => $e->getMessage(), 'line' => $e->getLine()]);
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            $walletData = $this->financeUserWallet->get_wallet($userId);
            $diamonNum = $walletData['diamond_balance'];
            $propNum = $this->luckDrawModel->getAvail($luckId, $userId);
            $data = [
                'diamond' => $diamonNum,
                'prop' => $propNum
            ];
        } while (false);
        return compact('code', 'data', 'msg');
    }

    /**
     * 兑换爱心币
     */
    public function hookBuy($num, $userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $luckId = 1003;
        do {
            //获取所需钻石总额
            $luckDrawInfo = $this->luckDrawModel->luckDrawInfo(1000);
            $luckDrawPrice = empty($luckDrawInfo['price']) ? 0 : $luckDrawInfo['price'];
            $needTotalDiamond = $luckDrawPrice * $num;
            //查询当前用户可用钻石
            $walletData = $this->financeUserWallet->get_wallet($userId);
            if ($walletData['diamond_balance'] < $needTotalDiamond) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            DB::beginTransaction();
            try {
                //扣除钻石
                $this->FinanceDiamond->inc($userId, 0, 0, 6, -$needTotalDiamond, '兑换道具爱心币');
                //增加道具
                $ok = $this->luckDrawModel->addProp($luckId, $userId, $num);
                //道具保存成功则增加日志
                if ($ok) {
                    $ok = $this->luckDrawModel->addPropLog($luckId, $userId, 1000, $num);
                }

                //赠送头像框
                $goodId = $this->senHeadGoodsId;
                $goodInfo = $this->mall_model->getMallGoodByGoodsId($goodId);
                if (empty($goodInfo)) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $skuList = $this->mall_model->getSkuDataByGoods($goodId);
                if (empty($skuList[0])) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $goodMap[$goodId]['goods_name'] = $goodInfo['goods_name'];
                $goodMap[$goodId]['goods_type'] = $goodInfo['goods_type'];
                $goodMap[$goodId]['sku_id'] = $skuList[0]['sku_id'];
                //有效期
                $timeLimit = $num * 3600;
                //商品增加
                $this->mall_model->shoppingAct(
                    11,
                    $userId,
                    $goodId,
                    $goodMap[$goodId]['goods_name'],
                    $goodMap[$goodId]['goods_type'],
                    $goodMap[$goodId]['sku_id'],
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    2
                );
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_hopeLuck', 'error 兑换爱心币', ['msg' => $e->getMessage(), 'line' => $e->getLine()]);
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            $walletData = $this->financeUserWallet->get_wallet($userId);
            $diamonNum = $walletData['diamond_balance'];
            $propNum = $this->luckDrawModel->getAvail($luckId, $userId);
            $data = [
                'diamond' => $diamonNum,
                'prop' => $propNum
            ];
        } while (false);
        return compact('code', 'data', 'msg');
    }

    /**
     * 星球夺宝兑换爱心币
     */
    public function popBuy($num, $userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $luckId = 1003;
        do {
            //获取所需钻石总额
            $luckDrawInfo = $this->luckDrawModel->luckDrawInfo(1000);
            $luckDrawPrice = empty($luckDrawInfo['price']) ? 0 : $luckDrawInfo['price'];
            $needTotalDiamond = $luckDrawPrice * $num;
            //查询当前用户可用钻石
            $walletData = $this->financeUserWallet->get_wallet($userId);
            if ($walletData['diamond_balance'] < $needTotalDiamond) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            DB::beginTransaction();
            try {
                //扣除钻石
                $this->FinanceDiamond->inc($userId, 0, 0, 6, -$needTotalDiamond, '兑换道具爱心币');
                //增加道具
                $ok = $this->luckDrawModel->addProp($luckId, $userId, $num);
                //道具保存成功则增加日志
                if ($ok) {
                    $ok = $this->luckDrawModel->addPropLog($luckId, $userId, 1000, $num);
                }

                //赠送头像框
                $goodId = $this->senStarGoodsId;
                $goodInfo = $this->mall_model->getMallGoodByGoodsId($goodId);
                if (empty($goodInfo)) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $skuList = $this->mall_model->getSkuDataByGoods($goodId);
                if (empty($skuList[0])) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $goodMap[$goodId]['goods_name'] = $goodInfo['goods_name'];
                $goodMap[$goodId]['goods_type'] = $goodInfo['goods_type'];
                $goodMap[$goodId]['sku_id'] = $skuList[0]['sku_id'];
                //有效期
                $timeLimit = $num * 3600;
                //商品增加
                $this->mall_model->shoppingAct(
                    11,
                    $userId,
                    $goodId,
                    $goodMap[$goodId]['goods_name'],
                    $goodMap[$goodId]['goods_type'],
                    $goodMap[$goodId]['sku_id'],
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    2
                );
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_hopeLuck', 'error 兑换爱心币', ['msg' => $e->getMessage(), 'line' => $e->getLine()]);
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            $walletData = $this->financeUserWallet->get_wallet($userId);
            $diamonNum = $walletData['diamond_balance'];
            $propNum = $this->luckDrawModel->getAvail($luckId, $userId);
            $data = [
                'diamond' => $diamonNum,
                'prop' => $propNum
            ];
        } while (false);
        return compact('code', 'data', 'msg');
    }

    /**
     * 获取资产信息
     */
    public function balance($userId)
    {
        $luckId = 1000;
        $used = $this->luckDrawModel->getUsed($userId, $luckId);
        $propNum = $this->luckDrawModel->getAvail($luckId, $userId);
        $data = [
            'prop' => $propNum,
            'exp' => $used,
        ];
        return $data;
    }

    /**
     * 获取海洋世界资产信息
     */
    public function hookBalance($userId)
    {
        $luckId = 1003;
        $used = $this->luckDrawModel->getUsed($userId, $luckId);
        $propNum = $this->luckDrawModel->getAvail($luckId, $userId);
        $walletData = $this->financeUserWallet->get_wallet($userId);
        $diamonNum = $walletData['diamond_balance'];
        $data = [
            'prop' => $propNum,
            'diamond' => $diamonNum,
            'exp' => $used,
        ];
        return $data;
    }

    /**
     * 获取用户抽奖记录
     */
    public function wishLuckAwardListByUserId($page, $limit, $userId)
    {
        $data = [];
        do {
            $where = [];
            //今天
            $where['user_id'] = $userId;
            $list = $this->luckDrawModel->wishLuckAllAwardList($page, $limit, $where);
            $listEx = [];
            if (!empty($list)) {
                $userIds = array_column($list, 'user_id');
                $userList = $this->userModel->get_users_by_ids($userIds);
                $userList = array_column($userList, null, 'user_id');

                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'image', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach ($list as $key => $v) {
                    if (empty($userList[$v['user_id']])) {
                        continue;
                    }
                    if (empty($giftList[$v['gift_id']])) {
                        continue;
                    }

                    $newArr = [
                        'type' => 1, //奖品类型 1、礼物 2、商品 
                        'luckId' => $v['pool_id'],
                        'userId' => $v['user_id'],
                        'awardId' => $v['order_id'],
                        'timeLimit' => 0,
                        'name' => $giftList[$v['gift_id']]['name'],
                        'image' => build_image($giftList[$v['gift_id']]['image']),
                        "animateResource" => '',
                        'price' => $giftList[$v['gift_id']]['price'],
                        'num' => $v['gift_num'],
                        'aperture' => $this->_getAperture($giftList[$v['gift_id']]['price']),
                        'nickname' => $userList[$v['user_id']]['nickname'],
                        'createdAt' => $v['created_at'],
                    ];
                    $listEx[] = $newArr;
                }
            }

            $data = $listEx;
        } while (false);

        return $data;
    }

    /**
     * 获取单次抽奖价格
     */
    public function getPrice($luckId)
    {
        $luckDrawInfo = $this->luckDrawModel->luckDrawInfo($luckId);
        $luckDrawPrice = empty($luckDrawInfo['price']) ? 0 : $luckDrawInfo['price'];
        return ['price' => $luckDrawPrice];
    }

    /**后台配置 */

    /**
     * 编辑心心相印配置
     */
    public function editWishLuckConfig($upData = [])
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($upData)) {
                break;
            }
            $res = $this->luckDrawModel->editWishLuckConfig($upData);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印设置奖池开启/关闭
     */
    public function wishLuckSetPoolStatus($poolId, $poolStatus)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($poolId) || empty($poolStatus)) {
                break;
            }
            //配置
            $config = $this->luckDrawModel->getWishPoolConfig();
            if (empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //奖池
            $pool = $this->luckDrawModel->getWishLuckPool();
            if (empty($pool[$poolId])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $pool[$poolId];
            $poolStatus = ($poolStatus == 1) ? 1 : 2;
            //开启
            if ($poolStatus == 1) {
                //区间内的奖池必须关闭
                $flag = 0;
                $openPool = []; //已开启的奖池
                foreach ($pool as $val) {
                    if ($val['status'] != 1) {
                        continue;
                    }
                    $openPool = $val;
                    //个人池不校验次数区间
                    if (in_array($val['pool_type'], [2, 3]) || in_array($poolInfo['pool_type'], [2, 3])) {
                        continue;
                    }
                    //校验次数区间
                    if ($val['pool_type'] == $poolInfo['pool_type']) {
                        if ($val['min_num'] <= $poolInfo['min_num'] && $poolInfo['min_num'] <= $val['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 1:与现有生效奖池' . $val['pool_name'] . '（' . $val['id'] . '）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                        if ($val['min_num'] <= $poolInfo['max_num'] && $poolInfo['max_num'] <= $val['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 2:与现有生效奖池' . $val['pool_name'] . '（' . $val['id'] . '）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                        if ($poolInfo['min_num'] <= $val['min_num'] && $val['min_num'] <= $poolInfo['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 3:与现有生效奖池' . $val['pool_name'] . '（' . $val['id'] . '）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                        if ($poolInfo['min_num'] <= $val['max_num'] && $val['max_num'] <= $poolInfo['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 4:与现有生效奖池' . $val['pool_name'] . '（' . $val['id'] . '）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                    }
                }
                if ($flag == 1) {
                    break;
                }

                //奖池配置数据是否有效
                $poolList = $this->luckDrawModel->getWishLuckPoolConfig($poolId);
                if (empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '获取奖池配置失败';
                    break;
                }
                $flag = 0;
                $giftNumAll = 0;
                $inDiamondNum = 0; //总消耗钻石数
                $outDiamondNum = 0; //总产出钻石数
                foreach ($poolList as $val) {
                    if (empty($val['gift_id'])) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '奖池配置 序号' . $val['item_no'] . '未配置礼物';
                        $flag = 1;
                        break;
                    }
                    $giftNumAll = $giftNumAll + $val['gift_num'];

                    $giftInfo = $this->giftModel->getGift(['gift_id' => $val['gift_id']], ['gift_id', 'name', 'image', 'price']);
                    $outDiamondNum = $outDiamondNum + ($giftInfo['price'] * $val['gift_num']);
                    $inDiamondNum = $inDiamondNum + (200 * $config['need_num'] * $val['gift_num']);
                }
                if ($giftNumAll < 1) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置 礼物数量总和不足1';
                    $flag = 1;
                    break;
                }
                // 奖池的爆出/消耗钻石数小于等于115%才可开启成功
                $rate = round($outDiamondNum / $inDiamondNum, 2);
                if ($rate > 1.5) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置 奖池的爆出:' . $outDiamondNum . ' /消耗钻石数:' . $inDiamondNum . ' 小于等于115%才可开启成功';
                    $flag = 1;
                    break;
                }
                if ($flag == 1) {
                    break;
                }

                //和已开启的奖池比较是否礼物一致
                if (!empty($openPool)) {
                    $openPoolList = $this->luckDrawModel->getWishLuckPoolConfig($openPool['id']);

                    if (empty($openPoolList)) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '已开启奖池配置异常';
                        break;
                    }
                    $openPoolGift = array_column($openPoolList, 'gift_id', 'item_no');
                    $poolGift = array_column($poolList, 'gift_id', 'item_no');
                    foreach ($openPoolGift as $k => $v) {
                        if ($poolGift[$k] != $v) {
                            $code = Hint::PARAM_ERROR;
                            $msg = '奖池配置 礼物ID与已开启奖池不一致,奖池序号:' . $k;
                            $flag = 1;
                            break;
                        }
                    }
                    if ($flag == 1) {
                        break;
                    }
                }
                //重制奖池
                $res = $this->wishLuckPoolReset($poolId);
                if ($res['code'] != Hint::SUCCESS) {
                    return $res;
                }
            }

            $res = $this->luckDrawModel->editWishLuckPool($poolId, ['status' => $poolStatus]);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印保存奖池配置
     */
    public function wishLuckSavePoolConfig($poolId, $poolList)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($poolId) || empty($poolList)) {
                break;
            }
            $poolInfo = $this->luckDrawModel->getWishLuckPoolById($poolId);
            if (empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //奖池需关闭才可改
            if ($poolInfo['status'] != 2) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池未关闭';
                break;
            }
            $poolMap = $this->luckDrawModel->getPoolConfig($poolId);
            if (empty($poolMap)) {
                $code = Hint::PARAM_ERROR;
                $msg = '获取奖池配置失败';
                break;
            }
            $poolMap = array_column($poolMap, null, 'id');
            //过滤
            $flag = 0;
            foreach ($poolList as $val) {
                if (empty($val['gift_id'])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置礼物ID不可为空';
                    $flag = 1;
                    break;
                }
                if (empty($poolMap[$val['id']])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置ID错误';
                    $flag = 1;
                    break;
                }
            }
            if ($flag == 1) {
                break;
            }

            //更新
            DB::beginTransaction();
            try {
                foreach ($poolList as $val) {
                    $id = $val['id'];
                    $giftId = $val['gift_id'];
                    $giftNum = $val['gift_num'];
                    $res = $this->luckDrawModel->editWishLuckPoolConfig($poolId, $id, $giftId, $giftNum);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_wishluck', 'error 保存错误', ['msg' => $e->getMessage()]);
                $code = Hint::ERROR;
                $msg = '更新系统异常';
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印新增奖池
     */
    public function wishLuckAddPool($poolName, $minNum, $maxNum, $poolType, $ifDefault)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($poolName)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            if (in_array($poolType, [1]) && (empty($minNum) || empty($maxNum))) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //个人池 默认只能有一个
            if (in_array($poolType, [2, 3])) {
                if ($ifDefault == 1) {
                    $defaultPool = $this->luckDrawModel->getWishLuckPoolByDefault($poolType);
                    if (!empty($defaultPool)) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '个人池 默认只能有一个';
                        break;
                    }
                }
                $minNum = $maxNum = 0;
            }

            //新增
            DB::beginTransaction();
            try {
                $poolId = $this->luckDrawModel->addWishLuckPool($poolName, $minNum, $maxNum, $poolType, $ifDefault);
                if (empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '新增奖池失败';
                    DB::rollBack();
                    break;
                }
                $flag = 0;
                for ($i = 1; $i <= 17; $i++) {
                    $pcId = $this->luckDrawModel->addWishLuckPoolConfig($poolId, $i);
                    if (empty($poolId)) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '新增奖池配置失败';
                        $flag = 1;
                        break;
                    }
                }
                if ($flag == 1) {
                    DB::rollBack();
                    break;
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $code = Hint::ERROR;
                $msg = '新增系统异常';
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印编辑奖池
     */
    public function wishLuckEditPool($poolId, $poolName, $minNum, $maxNum, $ifDefault)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($poolId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $this->luckDrawModel->getWishLuckPoolById($poolId);
            if (empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //奖池需关闭才可改
            if ($poolInfo['status'] != 2) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池未关闭';
                break;
            }
            //个人池 默认只能有一个
            if (in_array($poolInfo['pool_type'], [2, 3])) {
                if ($ifDefault == 1) {
                    $defaultPool = $this->luckDrawModel->getWishLuckPoolByDefault($poolInfo['pool_type']);
                    if (!empty($defaultPool) && $defaultPool['id'] != $poolId) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '个人池 默认只能有一个';
                        break;
                    }
                }
                $minNum = $maxNum = 0;
            }

            //更新
            $this->luckDrawModel->editWishLuckPool($poolId, ['pool_name' => $poolName, 'min_num' => $minNum, 'max_num' => $maxNum, 'if_default' => $ifDefault]);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印更新奖池缓存
     */
    public function wishLuckPoolReset($poolId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if (empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:参数错误';
                    break;
                }
                $poolInfo = $this->luckDrawModel->getWishLuckPoolById($poolId);
                if (empty($poolInfo)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }

                $poolList = $this->luckDrawModel->getWishLuckPoolConfig($poolId);
                if (empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:数据获取失败';
                    break;
                }

                
                $giftList = array_column($poolList, 'gift_num', 'id');
                if (in_array($poolInfo['pool_type'], [2, 3])) {
                    $this->luckDrawModel->makeWishLuckSelfPoolData($poolId, $giftList);
                } else {
                    $this->luckDrawModel->makeWishLuckPoolData($poolId, $giftList);
                }
                
                
            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '更新奖池缓存异常:' . $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印配置剩余数量
     */
    public function wishLuckPoolConfigNum($poolId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if (empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                $poolList = $this->luckDrawModel->getWishLuckPoolConfig($poolId);
                if (empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }

                $hasList = $this->luckDrawModel->getWishLuckPoolData($poolId);
                $hasList = array_column($hasList, 'num', 'id');

                $giftIds = array_column($poolList, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach ($poolList as $key => $val) {
                    $val['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                    $val['gift_price'] = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                    $val['less_num'] = empty($hasList[$val['id']]) ? 0 : $hasList[$val['id']];
                    $val['draw_num'] = $val['gift_num'] - $val['less_num'];

                    $poolList[$key] = $val;
                }
                $data = $poolList;
            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '异常:' . $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印新增白名单
     */
    public function wishLuckAddWhite($userId, $giftId, $adminId = 0)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($userId) || empty($giftId) || empty($adminId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //新增
            $whiteId = $this->luckDrawModel->addWishLuckWhite($userId, $giftId, $adminId);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印删除白名单
     */
    public function wishLuckDelWhite($whiteId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($whiteId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $res = $this->luckDrawModel->delWishLuckWhite($whiteId);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印取消投放白名单
     */
    public function wishLuckCancelWhite($whiteId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($whiteId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $res = $this->luckDrawModel->cancelWishLuckWhite($whiteId);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 新增心心相印展示礼物
     */
    public function wishLuckAddGift($giftId, $sort)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($giftId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //新增
            $whiteId = $this->luckDrawModel->wishLuckAddGift($giftId, $sort);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印删除展示礼物
     */
    public function wishLuckDelGift($id)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($id)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $res = $this->luckDrawModel->wishLuckDelGift($id);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印新增个人池用户
     */
    public function wishLuckAddPoolUser($userId, $poolId, $outDiamondNum, $adminId = 0)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($userId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //判断是否存在
            $poolUserInfo = $this->luckDrawModel->getWishLuckPoolUser($userId);
            if (!empty($poolUserInfo)) {
                $code = Hint::PARAM_ERROR;
                $msg = '用户已存在,不可重复添加';
                break;
            }
            //获取心心相印奖池根据ID
            $poolInfo = $this->luckDrawModel->getWishLuckPoolById($poolId);
            if (empty($poolInfo) || $poolInfo['status'] != 1 || !in_array($poolInfo['pool_type'], [2, 3])) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池不存在或未开启或不是个人池';
                break;
            }
            if ($poolInfo['pool_type'] == 2 && $outDiamondNum > 0) {
                $code = Hint::PARAM_ERROR;
                $msg = '亏损池移除钻石数必须是负数';
                break;
            }
            if ($poolInfo['pool_type'] == 3 && $outDiamondNum < 0) {
                $code = Hint::PARAM_ERROR;
                $msg = '盈利池移除钻石数必须是正数';
                break;
            }

            //初始化心心相印个人奖池配置数据缓存指定用户
            $poolConfigMap = $this->luckDrawModel->getWishLuckPoolConfig($poolId);
            if (empty($poolConfigMap)) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池配置获取失败';
                break;
            }
            $poolConfigMap = array_column($poolConfigMap, 'gift_num', 'id');
            $this->luckDrawModel->makeWishWheelSelfPoolDataByPoolIdUserId($poolId, $userId, $poolConfigMap);

            //新增
            $whiteId = $this->luckDrawModel->addWishLuckPoolUser($userId, $adminId, $poolId, $outDiamondNum);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印删除个人池用户
     */
    public function wishLuckDelPoolUser($id, $adminId = 0)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($id)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //判断是否存在
            $poolUserInfo = $this->luckDrawModel->getWishLuckPoolUserById($id);
            if (empty($poolUserInfo) || $poolUserInfo['is_delete'] == 1) {
                break;
            }

            $res = $this->luckDrawModel->wishLuckDelPoolUser($id, $poolUserInfo['user_id'], $adminId);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //查看个人奖池配置剩余数量
    public function wishLuckPoolSelfConfigNum($poolId, $userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if (empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                $poolInfo = $this->luckDrawModel->getWishLuckPoolById($poolId);
                if (empty($poolInfo)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                if (!in_array($poolInfo['pool_type'], [2, 3])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '不是个人奖池';
                    break;
                }

                //用户是否在
                $poolUserInfo = $this->luckDrawModel->getWishLuckPoolUser($userId);
                if (empty($poolUserInfo) || $poolUserInfo['pool_id'] != $poolId) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '用户不在此个人池中';
                    break;
                }

                $poolList = $this->luckDrawModel->getWishLuckPoolConfig($poolId);
                if (empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:数据获取失败';
                    break;
                }

                $hasList = $this->luckDrawModel->getWishLuckSelfPoolData($poolId, $userId);
                $hasList = array_column($hasList, 'num', 'id');

                $giftIds = array_column($poolList, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach ($poolList as $key => $val) {
                    $val['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                    $val['gift_price'] = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                    $val['less_num'] = empty($hasList[$val['id']]) ? 0 : $hasList[$val['id']];
                    $val['draw_num'] = $val['gift_num'] - $val['less_num'];

                    $poolList[$key] = $val;
                }
                $data = $poolList;
            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '异常:' . $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印新增奖池白名单
     */
    public function wishLuckAddPoolWhite($userId, $giftId, $adminId = 0)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($userId) || empty($giftId) || empty($adminId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //个人池用户
            $poolUser = $this->luckDrawModel->getWishLuckPoolUserId($userId);
            if (!empty($poolUser)) {
                $code = Hint::PARAM_ERROR;
                $msg = '用户在个人池 不可添加奖池白名单';
                break;
            }

            //获取用户当前抽奖的奖池
            //奖池
            $pool = $this->luckDrawModel->getWishLuckPool();
            $basePoolList = []; //普通池的
            $userPoolList = []; //用户个人池的
            foreach ($pool as $val) {
                if ($val['status'] != 1) {
                    continue;
                }
                //奖池配置数据
                $poolConfig = $this->luckDrawModel->getWishLuckPoolConfig($val['id']);
                if (empty($poolConfig)) {
                    continue;
                }
                $val['poolConfig'] = $poolConfig;
                //普通池
                if ($val['pool_type'] == 1) {
                    $basePoolList[] = $val;
                }
            }
            $poolList = []; //已开启的奖池
            if (empty($poolUser)) {
                $poolList = $basePoolList;
            }
            if (empty($poolList)) {
                $code = Hint::WAIT_OPEN;
                $msg = '创建失败，当前没有已开启的奖池';
                break;
            }

            //用户总抽奖记录数
            $drawNumNow = $drawNum = $this->luckDrawModel->getDrawCountByThreeDays($userId);
            $drawNumNow = $drawNumNow + 1;

            $usePool = []; //使用的奖池
            //在范围的
            foreach ($poolList as $val) {
                if ($val['min_num'] <= $drawNumNow && $drawNumNow <= $val['max_num']) {
                    $usePool = $val;
                }
            }
            //上一个
            $prevNum = 0;
            if (empty($usePool)) {
                foreach ($poolList as $val) {
                    if ($val['max_num'] <= $drawNumNow && $prevNum <= $val['max_num']) {
                        $usePool = $val;
                        $prevNum = $val['max_num'];
                    }
                }
            }
            //下一个
            $nextNum = 0;
            if (empty($usePool)) {
                foreach ($poolList as $val) {
                    if ($val['min_num'] >= $drawNumNow && ($nextNum == 0 || $nextNum >= $val['min_num'])) {
                        $usePool = $val;
                        $nextNum = $val['min_num'];
                    }
                }
            }
            //还是没有取第一个
            if (empty($usePool)) {
                $usePool = $poolList[0];
            }
            $poolId = $usePool['id'];

            $poolConfigId = 0;
            foreach ($usePool['poolConfig'] as $val) {
                if ($val['gift_id'] == $giftId) {
                    $poolConfigId = $val['id'];
                }
            }
            $is_into = 0;
            $configId = 0;
            if(empty($poolConfigId)){
                //再查下投入池中的配置数据
                $intoExgiftList = $this->luckDrawModel->getExPoolGifts($poolId);
                foreach($intoExgiftList as $val) {
                    if($val['gift_id'] == $giftId) {
                        $poolConfigId = $poolId;
                        $configId = $val['id'];
                        $is_into = 1;
                    }
                }
            }
            

            if (empty($poolConfigId)) {
                $code = Hint::WAIT_OPEN;
                $msg = '创建失败，用户将抽取奖池配置中无此礼物';
                break;
            }

            //自指定奖池中抽取指定的余量
            if (in_array($usePool['pool_type'], [2, 3]) && $is_into==0) {
                //个人池
                $res = $this->luckDrawModel->drawWishLuckAppoint($usePool['id'], $poolConfigId, $userId);
            }elseif($is_into == 1){
                $res = $this->luckDrawModel->drawWishExWheelWhite($poolConfigId, $configId);
            }else {
                //普通
                $res = $this->luckDrawModel->drawWishLuckAppoint($usePool['id'], $poolConfigId, 0);
            }
            if ($res) {
                //新增
                $whiteId = $this->luckDrawModel->addWishLuckWhite($userId, $giftId, $adminId, $poolId);
                if (!$whiteId) {
                    $code = Hint::WAIT_OPEN;
                    $msg = '创建失败，奖池余量扣除成功,数据写入失败';
                    break;
                }
            } else {
                $code = Hint::WAIT_OPEN;
                $msg = '创建失败，奖池无余量';
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印奖池更新阀值
     */
    public function wishLuckSetUserPoolConfig($poolId, $params = [])
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($poolId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $this->luckDrawModel->getWishLuckPoolById($poolId);
            if (empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //奖池需关闭才可改
            if (!in_array($poolInfo['pool_type'], [2, 3])) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池不是个人池';
                break;
            }

            //亏损池
            if ($poolInfo['pool_type'] == 2) {
                if (!empty($params['in_profit_loss']) && $params['in_profit_loss'] < 0) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '亏损池进入钻石数必须大于0';
                    break;
                }
                if (!empty($params['in_profit_rate']) && $params['in_profit_loss'] < 100) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '亏损池进入返奖率必须大于100%';
                    break;
                }
            }

            //盈利池
            if ($poolInfo['pool_type'] == 3) {
                if (!empty($params['in_profit_loss']) && $params['in_profit_loss'] > 0) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '盈利池进入钻石数必须小于0';
                    break;
                }
                if (!empty($params['in_profit_rate']) && $params['in_profit_loss'] > 100) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '盈利池进入返奖率必须小于100%';
                    break;
                }
            }
            if (!empty($params['out_profit_rate']) && $params['out_profit_rate'] < 0) {
                $code = Hint::PARAM_ERROR;
                $msg = '个人池移除钻石比例必须大于0';
                break;
            }

            //更新
            $this->luckDrawModel->editWishLuckPool($poolId, $params);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 心心相印每日统计
     */
    public function statisticalData($ymd)
    {
        do {
            $dateSt = date('Y-m-d 00:00:00', strtotime($ymd));
            $dateEt = date('Y-m-d 23:59:59', strtotime($ymd));
            $info = $this->luckDrawModel->wishPoolStatistics($dateSt, $dateEt);

            $data = [];
            $data['ymd'] = date('Ymd', strtotime($ymd));
            $data['user_num'] = empty($info['user_num']) ? 0 : $info['user_num'];
            $data['draw_num'] = empty($info['draw_num']) ? 0 : $info['draw_num'];
            $data['prop_num'] = empty($info['prop_num']) ? 0 : $info['prop_num'];
            $data['prop_diamond_num'] = empty($info['prop_diamond_num']) ? 0 : $info['prop_diamond_num'];
            $data['reward_diamond_num'] = empty($info['reward_diamond_num']) ? 0 : $info['reward_diamond_num'];
            $data['profit_loss'] = $data['prop_diamond_num'] - $data['reward_diamond_num'];

            $this->luckDrawModel->addWishPoolStatistics($data);
        } while (false);

        return $data;
    }

    /**
     * 许愿池新增特殊玩法配置礼物
     */
    public function wishLuckPoolConfigChildAdd($insertStr, $type, $p_gift_id){
        do{
            $code = Hint::SUCCESS;
            $msg = '';
            $data = [];
            if(empty($insertStr)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $strToArr = json_decode($insertStr,true);
            $insert = [];
            
            foreach($strToArr as $v){
                //查看原有奖池的配置礼物id,必须保持一致
                $oldPoolsId = $this->luckDrawModel->getWishLuckPoolConfig($v['pool_id']);
                if(empty($oldPoolsId)){
                    $code = Hint::ERR_NORMAL;
                    $msg = '奖池不存在';
                    break;
                }
                //获取所有礼物id
                $allGiftIds = array_column($oldPoolsId,'gift_id');
                if(!in_array($v['child_gift_id'], $allGiftIds)){
                    $code = Hint::ERR_NORMAL;
                    $msg = '礼物id在奖池中不存在';
                    break;
                }
                if($v['child_gift_id'] == $p_gift_id){
                    $code = Hint::ERR_NORMAL;
                    $msg = '礼物id不可为父级礼物id';
                    break;
                }
                $pGiftinfo = $this->giftModel->get_gift($p_gift_id);
                $insert[] =[
                    'pool_id' => $v['pool_id'],
                    'pool_config_id' => $v['pool_config_id'],
                    'child_gift_id' => $v['child_gift_id'],
                    'gift_num' => $v['gift_num'],
                    'p_gift_id' => $p_gift_id,
                    'p_gift_type' => $pGiftinfo['gift_type'],
                    'created_at' => date('Y-m-d H:i:s')
                ];
            }
            if(empty($insert)){
                break;
            }
            try{
                DB::beginTransaction();
                $res = $this->luckDrawModel->insertSpPoolConfig($insert);
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                $msg = $e->getMessage();
                $code = Hint::ERR_DB_FAIL;
                break;
            }
        }while(false);
        return compact('code','data','msg');
    }

    /**
     * 许愿池编辑特殊玩法配置
     */
    public function wishLuckPoolConfigChildEdit($insertStr, $spid, $p_gift_id){
        do{
            $code = Hint::SUCCESS;
            $msg = '';
            $data = [];
            if(empty($insertStr)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $strToArr = json_decode($insertStr,true);
            $update = [];
            
            foreach($strToArr as $v){
                //查看原有奖池的配置礼物id,必须保持一致
                $oldPoolsId = $this->luckDrawModel->getWishLuckPoolConfig($v['pool_id']);
                if(empty($oldPoolsId)){
                    $code = Hint::ERR_NORMAL;
                    $msg = '奖池不存在';
                    break;
                }
                //获取所有礼物id
                $allGiftIds = array_column($oldPoolsId,'gift_id');
                if(!in_array($v['child_gift_id'], $allGiftIds)){
                    $code = Hint::ERR_NORMAL;
                    $msg = '礼物id在奖池中不存在';
                    break;
                }
                if($v['child_gift_id'] == $p_gift_id){
                    $code = Hint::ERR_NORMAL;
                    $msg = '礼物id不可为父级礼物id';
                    break;
                }
                $update =[
                    'pool_id' => $v['pool_id'],
                    'pool_config_id' => $v['pool_config_id'],
                    'child_gift_id' => $v['child_gift_id'],
                    'gift_num' => empty($v['gift_num']) ? 0 : $v['gift_num'],
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }
            if(empty($update)){
                break;
            }
            try{
                DB::beginTransaction();
                $res = $this->luckDrawModel->wishLuckPoolConfigChildEdit($update,$spid );
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                $msg = $e->getMessage();
                $code = Hint::ERR_DB_FAIL;
                break;
            }
        }while(false);
        return compact('code','data','msg');
    }

    /**
     * 许愿池删除特殊玩法配置
     */
    public function wishLuckPoolConfigChildDel($spid){
        do{
            $code = Hint::SUCCESS;
            $msg = '';
            $data = [];
            $update =[
                'is_deleted' => 1,
                'updated_at' => date('Y-m-d H:i:s')
            ];
            try{
                DB::beginTransaction();
                $res = $this->luckDrawModel->wishLuckPoolConfigChildEdit($update,$spid );
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                $code = Hint::ERR_DB_FAIL;
                break;
            }
        }while(false);
        return compact('code','msg','data');
    }

    //百抽处理玩法套盒
    public function roundHundred($userId, $drawLogList, $oldNum, $poolId, $poolConfigId, $poolConfigMap, $whiteId){
        $newArr = [];
        //查看是否是双重暴击
        $isDouble = $this->luckDrawModel->getDoubleStatus($userId);
        if($oldNum == 100){
            //查看是否有特殊套盒id
            $popGiftIdArr = array_unique(array_column($drawLogList,'gift_id'));
            $seaBoxInfo = $this->luckDrawModel->getPoolSpPoolInfo($poolId, array_values($popGiftIdArr));
            
            if(empty($isDouble) && !empty($seaBoxInfo) && empty($whiteId)){
                //随机取出一个套盒
                $seaBoxId = $seaBoxInfo[0]['p_gift_id'];
                //获取套盒礼物信息
                $configPoolId = $seaBoxInfo[0]['pool_config_id'];
                $seaBoxArr = $this->luckDrawModel->getWishLuckSpPoolConfig($poolId, $configPoolId, $seaBoxId,12);
                foreach($seaBoxArr as $k=>$val){
                    for($i = 0; $i< $val['gift_num']; $i++){
                        $arr = [
                            'gift_id' => $val['child_gift_id'],
                            'white_id' => 0,
                            'pool_id' => $poolId,
                            'item_no' => $val['id'],
                            'is_sp' => 12,
                        ];
                        array_push($newArr,$arr);
                    }
                }  
                $num = $oldNum - count($newArr);
                for($i=1;$i<=$num;$i++){
                    //查询指定玩法套盒中指定的礼物id(产品提供)
                    $newPopGiftId = $this->spPopGifts;
                    $key = array_rand($newPopGiftId);
                    $newGiftId = $newPopGiftId[$key];
                    $drawLog['gift_id'] = $newGiftId;
                    $drawLog['white_id'] = 0;
                    $drawLog['pool_id'] = $poolId;
                    $drawLog['item_no'] = $poolConfigMap[$poolConfigId]['item_no'];
                    $drawLog['is_sp'] = 0;
                    array_push($newArr, $drawLog);
                }
                $this->luckDrawModel->setNextDrawSp($userId);

            }elseif($isDouble && !empty($seaBoxInfo)){
                $newArr = $drawLogList;
                foreach($seaBoxInfo as $v){
                    $key = 'gift_id';
                    $value = $v['p_gift_id'];
                    $filterArr = array_filter($newArr, function ($item) use ($key, $value) {
                        return $item[$key] != $value;
                    });
                    $newArr = $filterArr;
                }
                $needNum = count($drawLogList) - count($newArr);
                for($i=1;$i<=$needNum;$i++){
                    //查询指定玩法套盒中指定的礼物id(产品提供)
                    $newPopGiftId = $this->spPopGifts;
                    $key = array_rand($newPopGiftId);
                    $newGiftId = $newPopGiftId[$key];
                    $drawLog['gift_id'] = $newGiftId;
                    $drawLog['white_id'] = 0;
                    $drawLog['pool_id'] = $poolId;
                    $drawLog['item_no'] = $poolConfigMap[$poolConfigId]['item_no'];
                    $drawLog['is_sp'] = 0;
                    array_push($newArr, $drawLog);
                }
                foreach($newArr as $k=>$again){
                    //因为2倍还得在抽一次
                    $res = $this->luckDrawModel->drawWishLuckAppoint($poolId, $again['pool_config_id']);
                    $drawLog = $again;
                    $drawLog['is_sp'] = 0;
                    $newArr[$k]['is_sp'] = 0;
                    array_push($newArr, $drawLog);
                }
                $this->luckDrawModel->delDouble($userId);
            }elseif($isDouble && empty($whiteId)){
                $newArr = $drawLogList;
                foreach($newArr as $keys => $agains){
                    //因为2倍还得在抽一次
                    $res = $this->luckDrawModel->drawWishLuckAppoint($poolId, $agains['pool_config_id']);
                    $drawLog = $agains;
                    $drawLog['is_sp'] = 0;
                    $newArr[$keys]['is_sp'] = 0;
                    array_push($newArr, $drawLog);
                }
                $this->luckDrawModel->delDouble($userId);
            }else{
                //查看是否有特殊套盒id
                $popGiftIdArr = array_unique(array_column($drawLogList,'gift_id'));
                $seaBoxInfo = $this->luckDrawModel->getPoolSpPoolInfo($poolId, array_values($popGiftIdArr));
                $seaBoxId = [];
                if(!empty($seaBoxInfo)){
                    $seaBoxId = array_column($seaBoxInfo,'p_gift_id');
                }
                if(!empty($seaBoxInfo)){
                    foreach($drawLogList as $key => $vv){
                        if(in_array($vv['gift_id'],$seaBoxId)){
                            //查询指定玩法套盒中指定的礼物id(产品提供)
                            $newPopGiftId = $this->spPopGifts;
                            $key = array_rand($newPopGiftId);
                            $newGiftId = $newPopGiftId[$key];
                            $drawLog['gift_id'] = $newGiftId;
                            $drawLog['white_id'] = 0;
                            $drawLog['pool_id'] = $poolId;
                            $poolInfo = $this->luckDrawModel->getNewPopPoolConfig([$newGiftId], $poolId);
                            $newPoolId = $poolInfo[0]['id'];
                            $drawLog['pool_config_id'] = $newPoolId;
                            $drawLog['item_no'] = $poolConfigMap[$newPoolId]['item_no'];
                            $drawLog['is_sp'] = 0;
                            $vv = $drawLog;
                        }
                        array_push($newArr,$vv);
                    }
                }else{
                    $newArr = $drawLogList;
                }
            }
        }else{
            $config = new SystemConfig();
            $color_num = $config->getKeyConfig("hope_color_num");
            if (empty($color_num) || !in_array($oldNum, $color_num)) {
                foreach($drawLogList as $index => $item){
                    if($item['is_sp'] == 13 && empty($whiteId)){
                        //1抽10抽退回彩蛋
                        $this->luckDrawModel->returnBox($poolId, $item['pool_config_id']);
                        //查询指定玩法套盒中指定的礼物id(产品提供)
                        $newPopGiftId = $this->spPopGifts;
                        $key = array_rand($newPopGiftId);
                        $newGiftId = $newPopGiftId[$key];
                        $drawLogList[$index]['gift_id'] = $newGiftId;
                        $poolInfo = $this->luckDrawModel->getNewPopPoolConfig([$newGiftId], $poolId);
                        $newPoolId = $poolInfo[0]['id'];
                        $drawLogList[$index]['pool_config_id'] = $newPoolId;
                        $drawLogList[$index]['item_no'] = $poolConfigMap[$newPoolId]['item_no'];
                        $drawLogList[$index]['is_sp'] = 0;
                        //替补需要扣除因为是小于100连
                        $this->luckDrawModel->drawWishLuckAppoint($poolId, $newPoolId);
                    }
                }
            }

            //查看是否有特殊套盒id
            $popGiftIdArr = array_unique(array_column($drawLogList,'gift_id'));
            $seaBoxInfo = $this->luckDrawModel->getPoolSpPoolInfo($poolId, array_values($popGiftIdArr));
            $seaBoxId = [];
            if(!empty($seaBoxInfo)){
                $seaBoxId = array_column($seaBoxInfo,'p_gift_id');
            }
            if(!empty($seaBoxInfo)){
                foreach($drawLogList as $key => $vv){
                    if(in_array($vv['gift_id'],$seaBoxId)){
                        //10抽退
                        $this->luckDrawModel->returnBox($poolId, $vv['pool_config_id']);
                        //查询指定玩法套盒中指定的礼物id(产品提供)
                        $newPopGiftId = $this->spPopGifts;
                        $key = array_rand($newPopGiftId);
                        $newGiftId = $newPopGiftId[$key];
                        $drawLog['gift_id'] = $newGiftId;
                        $drawLog['white_id'] = 0;
                        $drawLog['pool_id'] = $poolId;
                        $poolInfo = $this->luckDrawModel->getNewPopPoolConfig([$newGiftId], $poolId);
                        $newPoolId = $poolInfo[0]['id'];
                        $drawLog['pool_config_id'] = $newPoolId;
                        $drawLog['item_no'] = $poolConfigMap[$newPoolId]['item_no'];
                        $drawLog['is_sp'] = 0;
                        //替补需要扣除因为是小于100连
                        $this->luckDrawModel->drawWishLuckAppoint($poolId, $newPoolId);
                        $vv = $drawLog;
                    }
                    array_push($newArr,$vv);
                }
            }else{
                $newArr = $drawLogList;
            } 
        }
        return $newArr;
    }

    //白名单特殊配置五动乾坤时候百抽抽取逻辑
    public function drawSpGifts($poolId){
        //查询指定玩法套盒中指定的礼物id(产品提供)
        $newPopGiftId = $this->spPopGifts;
        $key = array_rand($newPopGiftId);
        $newGiftId = $newPopGiftId[$key];
        $poolInfo = $this->luckDrawModel->getNewPopPoolConfig([$newGiftId], $poolId);
        $newPoolId = $poolInfo[0]['id'];
        //替补需要扣除
        $this->luckDrawModel->drawWishLuckAppoint($poolId, $newPoolId);
        return $newPoolId;
    }

    /**
     * 心心相印自动兑换爱心币弹窗
     */
    public function wishLuckPop($userId, $num, $roomId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = new stdClass;
        $luckId = 1000;
        $popId = 1003;
        $todayPop = 0;
        $now = time();
        do {
            $num = abs($num);
            //配置
            $config = $this->luckDrawModel->getWishPoolConfig();
            if(empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $needNum = $config['need_num'] * $num;
            //用户爱心币数量
            $userLuckDrawProp = $this->luckDrawModel->getLuckDrawUserProp($userId, $popId);

            //爱心币价格
            $luckDrawInfo = $this->luckDrawModel->luckDrawInfo($luckId);
            $luckDrawPrice = empty($luckDrawInfo['price']) ? 0 : $luckDrawInfo['price'];

            //获取用户钱包信息
            $userWaltInfo = $this->financeUserWallet->get_wallet($userId);

            //查看今日是否弹窗
            if(Redis::SISMEMBER($this->todayLuckPopKey,$userId)){
                $todayPop = 1;
            }

            if($userLuckDrawProp['avail'] < $needNum) {
                $code = Hint::SUCCESS;
                $msg = '参与心心相印需要用爱心币，开启钻石兑换爱心币可以更便捷参与游戏'.PHP_EOL.'1张爱心币='.$luckDrawPrice.'钻石'.PHP_EOL.'您的钻石余额：'.$userWaltInfo['diamond_balance'];
                $data = [
                    'pop_msg' => $msg,
                    'is_open' => $todayPop,
                ];
            }else{
                $data = [
                    'pop_msg' => $msg,
                    'is_open' => 1,
                ]; 
            }
        }while(false);
        return compact('code','data','msg');
    }

    /**
     * 确认弹窗协议
     */
    public function wishLuckConfirm($userId){
        do{
            $code = Hint::SUCCESS;
            $msg = '';
            $data = [];
            if(Redis::SISMEMBER($this->todayLuckPopKey,$userId)){
                $code = Hint::ERR_NORMAL;
                $msg = '已确认';
                break;
            }
            Redis::SADD($this->todayLuckPopKey,$userId);
            $endDay = Carbon::today()->endOfDay()->toDateTimeString();
            $diffTime = (new Carbon)->diffInSeconds($endDay);
            Redis::EXPIRE($this->todayLuckPopKey,$diffTime);
        }while(false);
        
        return compact('code','data','msg');
    }
   
    /**
     * 自动兑换爱心币
     */
    public function autoExchangeCard($userLuckDrawProp, $needNum, $luckDrawPrice, $userId){
        do{
            $code = Hint::SUCCESS;
            $msg = '';
            $data = [];
            $buyNum = $needNum - $userLuckDrawProp['avail'];
            $costDiamond = $buyNum * $luckDrawPrice;
            //查看用户钱包
            $userWaltInfo = $this->financeUserWallet->get_wallet($userId);
            if($userWaltInfo['diamond_balance'] < $costDiamond){
                $code = Hint::ERR_NORMAL;
                $msg = '钻石不足';
                break;
            }
            try{
                DB::beginTransaction();
                //扣钻石
                $this->FinanceDiamond->inc($userId, 0, 0, 6, -$costDiamond , '自动兑换爱心币*'.$buyNum);
                //增加道具
                $ok = $this->luckDrawModel->addProp(1003, $userId, $buyNum);
                //道具保存成功则增加日志
                if ($ok) {
                    $ok = $this->luckDrawModel->addPropLog(1003, $userId, 1000, $buyNum);
                }
                //赠送头像框
                $goodId = $this->senHeadGoodsId;

                $goodInfo = $this->mall_model->getMallGoodByGoodsId($goodId);
                if(empty($goodInfo)) {
                    return [Hint::ERR_NORMAL, null];
                }
                $skuList = $this->mall_model->getSkuDataByGoods($goodId);
                if(empty($skuList[0])) {
                    return [Hint::ERR_NORMAL, null];
                }
                $goodMap[$goodId]['goods_name'] = $goodInfo['goods_name'];
                $goodMap[$goodId]['goods_type'] = $goodInfo['goods_type'];
                $goodMap[$goodId]['sku_id'] = $skuList[0]['sku_id'];
                //有效期
                $timeLimit = $buyNum*3600;
                //商品增加
                $this->mall_model->shoppingAct(
                    11,
                    $userId,
                    $goodId,
                    $goodMap[$goodId]['goods_name'],
                    $goodMap[$goodId]['goods_type'],
                    $goodMap[$goodId]['sku_id'],
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    2
                );
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 扣除钻石失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'costDiamond'=>$costDiamond]);
                $code = Hint::ERR_NORMAL;
                $msg = '钻石不足';
                break;
            }
        }while(false);
        return compact('code','data','msg');
        
    }
   
    //投入礼物展示列表
    public function wishLuckExGift(){
        do{
            $code = Hint::SUCCESS;
            $data = [];
            $msg = '';

            $exGifts = $this->luckDrawModel->getExGift();
            $data = $exGifts;
        }while(false);
        return compact('code','msg','data');
    }

    //海底世界投入展示礼物新增/编辑
    public function addWishPoolsExGiftList($giftids, $isOpen){
        do{
            $code = Hint::SUCCESS;
            $data = [];
            $msg = '';
            if(empty($giftids)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $insert = [
                'gift_ids' => $giftids,
                'is_open' => $isOpen,
                'created_at' => date('Y-m-d H:i:s',time()),
            ];
            try{
                $check = $this->luckDrawModel->getWishPoolsExGiftList();
                if(!empty($check)){
                    $update = [
                        'gift_ids' => $giftids,
                        'is_open' => $isOpen,
                        'updated_at' => date('Y-m-d H:i:s',time()),
                    ];
                    $res = $this->luckDrawModel->updateWishPoolsExGiftList($update, $check['id']);
                }else{
                    $res = $this->luckDrawModel->addWishPoolsExGiftList($insert);
                }
                
                if($res){
                    DB::commit();
                    Redis::del($this->exGiftIdsList);
                }
            }catch(\Exception $e){
                DB::rollBack();
                $code = Hint::ERR_DB_FAIL;
                $msg = $e->getMessage();
                break;
            }    
        }while(false);
        return compact('code','data','msg');
    }

    //新增奖池投入礼物
    public function addExGiftForPool($giftId, $nums, $poolId){
        do{
            $code = Hint::SUCCESS;
            $msg = '';
            $data = [];
            if(empty($giftId) || empty($nums) || empty($poolId)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            try{
                DB::beginTransaction();
                $insert = [
                    'gift_id' => $giftId,
                    'nums' => $nums,
                    'pool_id' => $poolId,
                    'use_num' => 0,
                    'created_at' => date('Y-m-d H:i:s',time())
                ];
                $res = $this->luckDrawModel->insertExGiftForPool($insert);
                if($res){
                    DB::commit();
                    //生成缓存
                    $perper = [
                        $res => $nums,
                    ];
                    $this->luckDrawModel->makeExPoolRedis($poolId, $perper);
                }
            }catch(\Exception $e){
                DB::rollBack();
                $code = Hint::ERR_DB_FAIL;
                $msg = $e->getMessage();
                break;
            }
        }while(false);
        return compact('code','data','msg');
    }

    //查看投入记录
    public function getExGiftForPoolList(){
        do{
            $code = Hint::SUCCESS;
            $msg = '';
            $data = [];
            //获取投放记录
            $res = $this->luckDrawModel->getExForPoolList();
            if(!empty($res)){
                //查看剩余数量
                foreach($res as &$v){
                    $hasList = $this->luckDrawModel->getWishWheelExPoolData($v['pool_id']);
                    $hasList = array_column($hasList, 'num', 'id');
                    $v['less_num'] = empty($hasList[$v['id']]) ? 0 : $hasList[$v['id']];
                }
                $data = $res;
            }
        }while(false);
        return compact('code','msg','data');
    }

    //投入奖池逻辑触发
    public function checkExDraw($userId, $poolId, $drawNums){
        //查看开关是否开启
        $openStatus = $this->luckDrawModel->getExGift();
        $istrue = 0;
        if(!empty($openStatus) && $openStatus['is_open'] == 1){
            //查看要抽取的奖池数量是否为0
            $leaveCounts = $this->luckDrawModel->leaveCountsExPoolGifts($poolId);
            if(!empty($leaveCounts)){
                //投硬币取概率70%不给,30%给
                $rand = rand(1, 100);
                if($rand > 70){
                    $istrue = 1;
                }
            }
        }
        return $istrue;
    }
}
